package httpMiddleware

import (
	"errors"
	"github.com/gin-gonic/gin"
	"go_gateway/dao"
	"go_gateway/middleware"
	"strings"
)

// HTTPHeaderTransferMiddleware
// @Description: 修改HTTP请求头
// @return gin.HandlerFunc
//
func HTTPHeaderTransferMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 1.获取服务信息
		serviceInterface, ok := c.Get("service")
		if !ok {
			middleware.ResponseError(c, 2001, errors.New("service not found"))
			c.Abort()
			return
		}
		serviceDetail := serviceInterface.(*dao.ServiceDetail)

		// 2.获取header头转换规则, 每条规则以","分割
		headTransfer := strings.Split(serviceDetail.HTTPRule.HeaderTransfor, ",")
		for _, item := range headTransfer {
			items := strings.Split(item, " ")
			if len(items) != 3 { // 参数不为3 非法规则
				continue
			}
			if items[0] == "add" || items[0] == "edit" {
				c.Request.Header.Set(items[1], items[2])
			}
			if items[0] == "del" {
				c.Request.Header.Del(items[1])
			}
		}
		c.Next()
	}
}
